#region license
/*
 * Copyright (C) 2007 CchenSoft.com
 * 
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License 2.1 or later, as
 * published by the Free Software Foundation. See the included License.txt
 * or http://www.gnu.org/copyleft/lesser.html for details.
 * 
 * Author: Billy Zhang
 */
#endregion

using System;
using System.IO;
using System.Web;
using CookComputing.XmlRpc;
using CchenSoft.Portal.Util;
using CchenSoft.Portal.Blog.Model;
using CchenSoft.Portal.Blog.Service;

namespace CchenSoft.Portal.Blog.Tracking
{
	/// <summary>
	/// Service used to receive pingbacks from remote clients.
	/// </summary>
	public class PingBackService : XmlRpcService
	{
		/// <summary>
		/// Method called by a remote client to ping this server.
		/// </summary>
		/// <param name="sourceURI">Source URI.</param>
		/// <param name="targetURI">Target URI.</param>
		/// <returns></returns>
		[XmlRpcMethod("pingback.ping", Description="Pingback server implementation")] 
		public string pingBack(string sourceURI, string targetURI)
		{
			string pageTitle;

			// GetPostIDFromUrl returns the postID
            int postId = ConvertUtil.ToInt32(Path.GetFileNameWithoutExtension(targetURI));

            if (postId == 0)
                throw new XmlRpcFaultException(33, "You did not link to a permalink");

            Uri sourceUrl = new Uri(sourceURI);
            Uri targetUrl = new Uri(targetURI);

            //// does the sourceURI actually contain the permalink ?
            if (sourceUrl == null || targetUrl == null || !Verifier.SourceContainsTarget(sourceUrl, targetUrl, out pageTitle))
                throw new XmlRpcFaultException(17, "Not a valid link.");

            ////PTR = Pingback - TrackBack - Referral
            PostComment comment = new PostComment();
            comment.Type = CommentType.PingTrack;

            comment.PostID = postId;
            comment.Title = pageTitle;
            comment.SourceUrl = sourceURI;
            comment.Content = pageTitle;

            PortletContext portletContext = (PortletContext)Context.Items["portlet_context"];
            portletContext.GetService<IBlogService>().SavePostComment(comment);
		
			return "thanks for the pingback on " + sourceURI ;
		}
	}
}

